<?php
/**
 *  @department : Commercial development.
 *  @description : This file is part of [huoyuan].
 */
namespace app\proxy\controller;

use app\proxy\proxyCenter\ProxyRequestControl;
use app\proxy\proxyCenter\ProxyRuleConfig;
use think\Controller;

/**
 * 路由重定向控制器.
 */
class ProxyRedirect extends Controller
{
    /**
     * @var ProxyControl 路由代理转发请求类
     */
    protected $proxyReqControl;

    /**
     * 根据商品sku/条码检查是否为对应入库单商品,并返回商品信息.
     */
    public function rewrite()
    {
        $param = $this->request->param(false);

        $url_info = $this->request->url();

        $method = $this->request->method();

        try {
            $this->proxyReqControl = new ProxyRequestControl(
                ProxyRuleConfig::$proxyHost . $this->parsingRoute($url_info),
                $method,
                $this->getCookie(),
                ProxyRuleConfig::$cookieHost
            );

            $this->proxyReqControl->gateWaySend($param);

            $res_cookie = $this->proxyReqControl->setCookieContent;

            if (!empty($res_cookie)) {
                //解析并处理cookie机制返回源请求
                $this->setResCookie($res_cookie);
            }

            return $this->proxyReqControl->responseContent;
        } catch (\Exception $e) {
            throw new \Exception($e);
            // return json(['status' => false, 'message' => '网站维护中, 请稍后~']);
        }
    }

    /**
     * 使用代理规解析源路由则返回代理路由.
     *
     * @throws Exception
     *
     * @return bool|string
     */
    public function parsingRoute($url_info)
    {
        //获取代理请求路由
        $pos = strpos($url_info, ProxyRuleConfig::$proxyRoute);
        return  substr_replace($url_info, '', $pos, strlen(ProxyRuleConfig::$proxyRoute));
    }

    /**
     * 从请求头中获取对应的key, 并设置当前源请求的cookie.
     *
     * @throws Exception
     *
     * @return bool|string
     */
    public function setResCookie($res_cookie)
    {
        $b = mb_strpos($res_cookie[0], ProxyRuleConfig::$sessionKey . '=') + mb_strlen(ProxyRuleConfig::$sessionKey . '=');
        $e = mb_strpos($res_cookie[0], ';') - $b;
        $session_id = mb_substr($res_cookie[0], $b, $e);

        cookie(ProxyRuleConfig::$sessionKey, $session_id);
    }

    /**
     * 获取当前源请求的cookie.
     *
     * @throws Exception
     *
     * @return bool|string
     */
    public function getCookie()
    {
        $cookie = cookie(ProxyRuleConfig::$sessionKey);

        if (!empty($cookie)) {
            $cookie_info = [
                ProxyRuleConfig::$sessionKey => $cookie,
            ];
        } else {
            $cookie_info = [];
        }

        return $cookie_info;
    }
}
